//
//  NotificationVC.m
//  coffee
//
//  Created by student4 on 2020/12/6.
//  Copyright © 2020 MOSAD. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "NotificationVC.h"
#import "../../util/NotificationRequest.h"

@interface NotificationVC()<UITableViewDelegate,UITableViewDataSource>{
}
@end

@implementation NotificationVC

-(void)viewDidLoad{
    _notificationview = [[NotificationView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [_notificationview setDataSource:self];
    [_notificationview setDelegate:self];;
    [self.view addSubview:_notificationview];
}
-(void)loadMsgs{
    if (_msg_list == nil) {
        _msg_list = [[NSMutableArray<Notification*> alloc]init];
    }
    [_msg_list removeAllObjects];
    [[NotificationRequest defaultNotificationRequest]getAllNotification:^(NSArray<Notification *> *msg_list) {
        for (Notification *n in msg_list) {
            [self->_msg_list addObject:n];
        }
        [[self notificationview]reloadData];
    } failure:^(NSString *reason) {
        NSLog(@"%@",reason);
    }];
}
#pragma mark UITableViewDataSource
-(NSInteger)tableView: (UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_msg_list count];
}

-(UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    NSString *cellID = [NSString stringWithFormat:@"cellID-%zd",indexPath.row];
    NotificationCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (nil == cell){
        cell = [[NotificationCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
    }
    [cell setupMsg:_msg_list[indexPath.row]];
    return cell;
}

-(CGFloat)tableView: (UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    return 60.0f;
}

-(void)tableView: (UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    Notification *msg = _msg_list[indexPath.row];
    if (!msg.Read) {
        [[NotificationRequest defaultNotificationRequest]readNotificationByID:[msg ID] success:^{
            [msg setRead:true];
            [tableView reloadData];
        } failure:^(NSString *reason) {
            NSLog(@"%@",reason);
        }];
    }
    
}
@end
